from django.shortcuts import render
from rest_framework.views import APIView

from users.utils import check_verify_token
from .serializers import RegisterCreatUserSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer
# Create your views here.
from users.models import Users

from rest_framework.response import Response

class RegisterPhoneCountAPIView(APIView):
    """
    查询手机号的个数
    GET: /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """
    def get(self,request,mobile):

        #通过模型查询获取手机号个数
        count = Users.objects.filter(mobile=mobile).count()
        #组织数据
        context = {
            'count':count,
            'phone':mobile
        }

        return Response(context)



class ResgisterUserNameView(APIView):

    """
    1 我们规定前端用get 方式把用户传递过来
    2定义url
    3实现业务逻辑

    /users/usernames/user——name/
    GET  /users/usernames/(?P<username>\w(5,20)/count/
    """
    def get(self,request,username):


        #满足条件的个数
        #count = 0 表示没有注册
        #西欧那天= 1 表示注册了
        count = Users.objects.filter(username=username).count()
        context = {
            'count':count,
            'username':username
        }

        #返回数据
        return Response(context)

    #前端联调目的是1接收能不能用2 返回的数据 能不能满足前端的要求



class RegisterCreatUserView(APIView):

    """
    1我们需要让前端把用户名，密码，确认密码，手机号，短信验证码，是否同意协议 传递过来
    2接收数据并进行验证
    3 杨峥没有问题就入库
    4返回响应
    """
    def post(self,request):
        #1接收参数
        data = request.data
        #2创建序列化器
        serializer = RegisterCreatUserSerializer(data=data)
        #校验
        serializer.is_valid(raise_exception=True)
        #3入库
        serializer.save()
        #4返回响应
        return Response(serializer.data)

from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import GenericAPIView

class RegisterCreateUser2View(CreateModelMixin, GenericAPIView):
    serializer_class = RegisterCreatUserSerializer

    def post(self, request):
        return self.create(request)

from rest_framework.generics import CreateAPIView
class RegisterCreateUser3View(CreateAPIView):
    serializer_class = RegisterCreatUserSerializer


# 分析选择哪个视图的思路：
# 1. APIView 可以实现所有的功能
# 2. 在APIView的基础上 对代码进行优化和封装就会发现问题
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny, IsAuthenticatedOrReadOnly
# class UserCenterInfoView(APIView):
#     """
#     1.登录用户点击 个人中心的时候，获取个人信息
#
#     1.登录用户
#     2.获取个人信息
#
#     GET     /users/infos/
#     """
#
#     #指定的视图中 设置权限
#     #    IsAuthenticated 登录用户（认证用户）
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#
#         #1.获取个人信息
#         # 我们现在采用的是 jwt token认证，只要前端传递的token是正确的 就可以确认 登录用户
#         # 登录用户 保存在了request.user中
#         user = request.user
#         #2. 创建序列化器
#         serializer = UserDetailSerializer(user)
#         #3.返回响应
#         return Response(serializer.data)



from rest_framework.generics import GenericAPIView
from rest_framework.mixins import RetrieveModelMixin
# class UserCenterInfoView(RetrieveModelMixin,GenericAPIView):
#
#
#     serializer_class = UserDetailSerializer
#
#     # 默认如果是根据 pk来获取数据的时候 需要设置 这个属性
#     # queryset = Users.objects.all()
#
#     def get_object(self):
#
#         return self.request.user
#
#     def get(self,request):
#
#         return self.retrieve(request)
from rest_framework.generics import RetrieveAPIView
class UserCenterInfoView(RetrieveAPIView):
    serializer_class = UserDetailSerializer

    def get_object(self):

        return self.request.user






# class UserEmailView(APIView):
#
#     """
#     必须是登录用户才可以访问
#     1.当用户输入邮箱内容 点击保存的时候， 前端发送请求给后端
#     2. 后端接受到数据之后，更新数据库
#     3. 给这个邮箱发送一条激活邮件
#     4. 返回响应
#
#     PUT         /users/emails/
#
#     """
#     permission_classes = [IsAuthenticated]
#
#     def put(self,request):
#
#         #1. 接受数据
#         data = request.data
#         user = request.user
#
#         # 2. 对数据进行校验
#         serializer = EmailSerializer(instance=user,data=data)
#         serializer.is_valid(raise_exception=True)
#         # 3. 更新数据
#         serializer.save()
#         # 4. 发送激活邮件
#
#         # 5. 返回响应
#         return Response(serializer.data)



from rest_framework.generics import UpdateAPIView
class UserEmailView(UpdateAPIView):

    serializer_class = EmailSerializer

    permission_classes = [IsAuthenticated]


    def get_object(self):
        return self.request.user



#地址
class AddressView(APIView):

    permission_classes = [IsAuthenticated]
    """
    POST        users/addresses/
    """

    def post(self,request):
        """
        1.接受前段提交的数据
        2.对数据进行校验
        3.保存数据
        4.返回响应

        """

        data = request.data

        serializer = AddressSerializer(data=data,context={'request':request})

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)


class UserEmailActiveView(APIView):




    #emails/verification/?token=xxx
    def get(self,request):

        #1.获取token
        token = request.query_params.get('token')

        from rest_framework import status
        if token is None:
            return Response({'msg':'缺少参数'},status=status.HTTP_400_BAD_REQUEST)
        #2.对token进行解析
        # {id:xxx,email:xxx}
        id = check_verify_token(token)
        if id is None:
            return Response({'msg': '信息错误'}, status=status.HTTP_400_BAD_REQUEST)
        #3.获取用户信息 修改激活状态
        try:
            user = Users.objects.get(id=id)
        except Users.DoesNotExist:
            return Response({'msg': '信息错误'}, status=status.HTTP_400_BAD_REQUEST)


        user.email_active=True
        user.save()

        return Response({'msg':'ok'})

